/**
 * All rights reserved by DigitNexus Technology INC.
 */
package com.xspace.android.xafcommon.download;

import android.graphics.Bitmap;
import android.os.Environment;
import android.os.StatFs;
import android.text.TextUtils;

import com.xspace.android.xafcommon.util.LogUtil;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;

public class FileUtils {
    public static final String PATH = Environment.getExternalStorageDirectory()
            .getPath();

    public static final String DOWNLOAD_TEMP_PATH = PATH;

    public static void initDir(String root, String dir) {
        if (TextUtils.isEmpty(root)) {
            initDir(dir);
        } else {
            String path = root + "/" + dir;
            LogUtil.d(path);
            File f = new File(path);
            if (!f.exists()) {
                boolean isMakeSuccess = f.mkdirs();
                LogUtil.d(isMakeSuccess + "");
            } else {
                LogUtil.d(f.exists() + " == true");
            }
        }
    }

    public static void initDir(String filePath) {
        String path = PATH + "/" + filePath;
        LogUtil.d(path);
        File f = new File(path);
        if (!f.exists()) {
            boolean isMakeSuccess = f.mkdirs();
            LogUtil.d(isMakeSuccess + "");
        } else {
            LogUtil.d(f.exists() + " == true");
        }
    }

    public static void initNewDir(String filePath) {
        File f = new File(DOWNLOAD_TEMP_PATH + "/" + filePath);
        if (!f.exists())
            f.mkdirs();
    }

    public static void initDownloadTempDir() {
        File f = new File(DOWNLOAD_TEMP_PATH);
        if (!f.exists())
            f.mkdirs();
    }

    public static String getName(String file) {
        if (file != null && !"".equals(file)) {
            int index = file.lastIndexOf("/");
            if (index != -1) {
                return file.substring(index + 1);
            } else {
                return "";
            }
        }
        return null;
    }

    public static void reName(String oldFile, String newFile) {
        if (oldFile != null && !"".equals(oldFile)) {
            File file = new File(oldFile);
            file.renameTo(new File(newFile));
        }

    }

    public static void moveFile(String tempLocation, String newLocation)
            throws IOException {
        File oldLocation = new File(tempLocation);
        if (oldLocation != null && oldLocation.exists()) {
            BufferedInputStream reader = new BufferedInputStream(
                    new FileInputStream(oldLocation));
            BufferedOutputStream writer = new BufferedOutputStream(
                    new FileOutputStream(newLocation, false));
            try {
                byte[] buff = new byte[8192];
                int numChars;
                while ((numChars = reader.read(buff, 0, buff.length)) != -1) {
                    writer.write(buff, 0, numChars);
                }
            } catch (IOException ex) {
            } finally {
                try {
                    if (reader != null) {
                        writer.close();
                        reader.close();
                    }
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
            }
        } else {
        }
    }

    public static String getPath() {
        return PATH;
    }

    public static String newFileName(String suffix) {
        return PATH + "/" + System.currentTimeMillis() + "." + suffix;
    }

    public static boolean deleteFile(String fileName) {
        boolean flag = false;
        File f = new File(fileName);
        if (f.exists()) {
            if (f.isFile()) {
                f.delete();
                flag = true;
            } else if (f.isDirectory()) {
                String[] filelist = f.list();
                for (int i = 0; i < filelist.length; i++) {
                    @SuppressWarnings("unused")
                    File readfile = new File(fileName + filelist[i]);
                    deleteFile(fileName + filelist[i]);
                    flag = true;
                }
            }
        }
        return flag;
    }

    public static boolean newFile(String fileName) {
        LogUtil.d(fileName);
        LogUtil.d("newFile");
        File f = new File(fileName);
        if (!f.exists()) {
            try {
                return f.createNewFile();
            } catch (FileNotFoundException notFound) {
                notFound.printStackTrace();
                boolean isMakeSuccess = f.mkdirs();
                if (isMakeSuccess) {
                    LogUtil.d("isMakeSuccess true");
                    try {
                        return f.createNewFile();
                    } catch (IOException e) {
                        LogUtil.d("f.createNewFile() true");
                        e.printStackTrace();
                    }
                } else {
                    LogUtil.d("isMakeSuccess false");
                }
            } catch (IOException e) {
                e.printStackTrace();
                boolean isMakeSuccess = f.mkdirs();
                if (isMakeSuccess) {
                    LogUtil.d("isMakeSuccess true");
                    try {
                        return f.createNewFile();
                    } catch (IOException e2) {
                        LogUtil.d("f.createNewFile() true");
                        e.printStackTrace();
                    }
                } else {
                    LogUtil.d("isMakeSuccess false");
                }
            }
        }
        return false;
    }

    public static String getExtension(String fileName) {
        int length = fileName.indexOf(".");
        return fileName.substring(length + 1);
    }

    public static boolean isFileExists(String fileName) {
        File f = new File(PATH + fileName);
        return f.isDirectory();
    }

    public static boolean isExists(String fileName) {
        File f = new File(fileName);
        if (f.exists()) {
            if (f.length() == 0)
                f.delete();
        }
        return f.exists();
    }

    public static String newFileName(String fileName, String suffix) {
        return PATH + "/" + fileName + "." + suffix;
    }

    public static boolean checkSDcard() {
        if (android.os.Environment.getExternalStorageState().equals(
                android.os.Environment.MEDIA_MOUNTED)) {
            return true;
        }
        return false;
    }

    public static boolean getAvailableStore() {
        StatFs statFs = new StatFs(Environment.getExternalStorageDirectory()
                .getPath());
        long blocSize = statFs.getBlockSize();
        long totalBlocks = statFs.getBlockCount();
        long availaBlock = statFs.getAvailableBlocks();
        long total = totalBlocks * blocSize;
        long availableSpare = availaBlock * blocSize;
        float result = availableSpare * 100 / total;
        if (result < 10)
            return false;
        else
            return true;
    }

    @SuppressWarnings("finally")
    public static HashMap<String, String> load(InputStream is) {
        String appInfo[] = null;
        HashMap<String, String> appMap = new HashMap<String, String>();
        try {
            DataInputStream bis = new DataInputStream(is);
            String txt = "";
            do {
                txt = bis.readLine();
                if (txt != null) {
                    txt = new String(txt.trim().getBytes("ISO-8859-1"), "UTF-8");
                    ;
                    appInfo = txt.split(":");
                    appMap.put(appInfo[0], appInfo[1]);
                }
            } while (txt != null && !"".equals(txt));
            bis.readLine();

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            return appMap;
        }
    }

    public static void saveFile(Bitmap bm, String fileName) {
        BufferedOutputStream bos = null;
        try {
            File dirFile = new File(PATH + "/nxb/img");
            if (!dirFile.exists()) {
                dirFile.mkdir();
            }
            File myCaptureFile = new File(PATH + "/nxb/img/" + fileName);
            bos = new BufferedOutputStream(new FileOutputStream(myCaptureFile));
            bm.compress(Bitmap.CompressFormat.JPEG, 80, bos);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            bm.recycle();
            if (bos != null) {
                try {
                    bos.flush();
                    bos.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

            }
        }
    }

}
